<template>
  <div>
    <div class="add">
      <el-card class="lh28">
        <div class="addOrderPopout">
          <!-- <div class="titleL">基本信息</div> -->
          <el-form ref="detail" :model="detail" :rules="rules" label-position="left">

            <el-form-item size="mini" label="人员属性">
              <el-radio-group v-model="detail.personType">
                <el-radio :label="1">总部</el-radio>
                <el-radio :label="2">院区</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item size="mini" label="姓名" prop="name">
              <el-input v-model="detail.name" class="w280" />
            </el-form-item>
            <el-form-item size="mini" label="手机号" prop="phone">
              <el-input v-model="detail.phone" class="w280" />
            </el-form-item>
            <el-form-item size="mini" label="岗位">
              <el-select
                v-model="detail.positionIds"
                multiple
                filterable
                placeholder="请选择"
                value-key="id"
                class="w280"
                @change="changepPsitionIds"
              >
                <el-option v-for="item in options.positionIds" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item size="mini" label="岗位属性">
              <el-select
                v-model="detail.positionAttributeIds"
                multiple
                filterable
                placeholder="请选择"
                value-key="id"
                class="w280"
                @change="changePositionAttributeIds"
              >
                <el-option
                  v-for="item in options.positionAttributeIds"
                  :key="item.id"
                  :label="item.dictValue"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="detail.personType == 1" size="mini" label="组织" prop="orgIds">
              <el-cascader
                ref="orgIds"
                v-model="detail.orgIds"
                class="w280"
                :options="options.org"
                :show-all-levels="false"
                :props="optionProps"
                clearable
              />
            </el-form-item>

            <el-form-item v-if="detail.personType == 2" size="mini" label="院区" required>
              <el-select
                v-model="yardId"
                filterable
                placeholder="请选择"
                value-key="id"
                class="w280"
                @change="changeYardIds"
              >
                <el-option v-for="item in options.yard" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="detail.personType == 2" size="mini" label="科室">
              <el-select
                v-model="detail.deptId"
                filterable
                placeholder="请选择"
                value-key="id"
                class="w280"
                clearable
                @focus="focusDeptIds"
                @change="$forceUpdate()"
              >
                <el-option v-for="item in options.dept" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>

            <el-form-item size="mini" label="三方编码" prop="code">
              <el-input v-model="detail.code" class="w280" />
            </el-form-item>
            <el-form-item size="mini" label="备注">
              <el-input v-model="detail.remark" type="textarea" class="w280" />
            </el-form-item>
            <div v-if="nameType != '详情'" class="footer">
              <el-button type="primary" size="small" @click="createDetail('detail')">提 交</el-button>
              <el-button size="small" @click="returnUpper">返 回</el-button>
            </div>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { personAdd, personUpdate, personDetail } from '@/api/personnel';
import { getDeptTree } from '@/api/organization';
import { yardPullList } from '@/api/courtyardAdmin';
import { pullList, attributePullList } from '@/api/post';
import { officeList } from '@/api/department';
// import { json } from 'stream/consumers';
class Detail {
  personType = 1;
  name = '';
  phone = '';
  orgIds = '';
  deptIds = [];
  deptId = '';
  yardIds = [];
  positionIds = [];
  positionAttributeIds = [];
  code = '';
  remark = '';
}

class Rules {
  name = [{ required: true, message: '请输入姓名', trigger: 'blur' }];
  orgIds = [{ required: true, message: '请选择组织', trigger: 'change' }];
  phone = [
    { required: true, message: '请填写手机号', trigger: 'change' },
    {
      pattern: /^1[3-9][0-9]{9}$/,
      message: '手机号格式不对',
      trigger: 'change'
    }
  ];
  // yardIds = [{ required: true, message: '请选择院区', trigger: 'change' }];
  code = [{ required: true, message: '请输入三方编码', trigger: 'blur' }];
}
class Options {
  positionIds = []
  positionAttributeIds = []
  org = []
  dept = []
  yard = []
  options = [
    { id: 1, name: '选项一' },
    { id: 2, name: '选项二' },
    { id: 3, name: '选项三' },
    { id: 4, name: '选项四' }
  ];
}
export default {
  name: 'CourtyardAdminDetail',
  data() {
    return {
      detail: new Detail(), // 分页
      options: new Options(), // 选项
      rules: new Rules(), // 表单校验
      attribute: [],
      nameType: '详情',
      yardId: '',
      deptIds: '',
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        disabled: 'autoCreate',
        emitPath: false,
        checkStrictly: true
      }

      // checkStrictly: true
    };
  },

  mounted() {
    // console.log(this.$route.query);
    this.nameType = this.$route.query.nameType;
    this.getOptions();
    if (this.nameType == '修改') {
      this.getDetail();
    }
  },
  methods: {
    async getOptions() {
      const positionIds = await pullList();
      this.options.positionIds = positionIds ? positionIds.data : '';
      try {
        const org = await getDeptTree({
          withOutAutoCreate: true
        });
        this.options.org = org ? this.getTreeData(org.data) : {};
      } catch (e) {
        this.options.org = [];
      }
      // console.log(res);
      const yard = await yardPullList({});
      this.options.yard = yard ? yard.data : '';
    },
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // 最后一级没有数据将children变成undefined
          data[i].children = undefined;
        } else {
          // children不为空时继续调用该方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    async getDetail() {
      const { data } = await personDetail({ id: this.$route.query.id });
      this.detail = data;

      this.changepPsitionIds();
      if (this.detail.personType == 2) {
        this.changeYardIds(this.detail.yardId, 'detail', data.deptId);
        this.detail.yardIds = [this.detail.yardId];
        this.yardId = this.detail.yardId;
      }
      this.detail.orgIds = this.detail.orgIds[0];
      // console.log(this.detail.yardId);
      // console.log(this.detail.deptId);
      // this.options.positionIds = data;
    },
    // 选择院区
    async changeYardIds(val, type, deptId) {
      // if (type == 'detail') {
      //   // console.log(e);
      // } else {
      //   // this.detail.yardIds = [];
      //   // this.detail.yardIds.push(e);
      //   // console.log(this.detail.yardIds);
      // }

      // console.log(e);
      try {
        const { data } = await officeList({
          yardIds: [val],
          filterOtherDept: 0
        });
        this.options.dept = data.list;
        // console.log(res);
        if (type == 'detail') {
          this.detail.deptId = deptId;
          this.detail.deptIds = [deptId];
        } else {
          this.detail.deptId = '';
          this.detail.yardIds = [val];
        }
        // console.log(this.detail.deptId);
        // console.log('成功' + this.detail.yardIds);
      } catch (e) {
        this.options.dept = [];
        this.detail.yardIds = [val];
        // console.log('失败' + this.detail.yardIds);
      }
    },
    // 科室获取焦点
    async focusDeptIds() {
      if (this.nameType == '新增') {
        if (!this.detail.yardIds.length) {
          this.$message({
            message: '请选择院区',
            type: 'warning'
          });
        }
      } else {
        if (!this.detail.yardIds) {
          this.$message({
            message: '请选择院区',
            type: 'warning'
          });
        }
      }
    },
    // 选择科室
    async changeDeptIds(e) {
      // this.detail.deptIds = [];
      // this.detail.deptIds.push(e);
      // console.log(this.detail.deptIds);
    },
    // 选择岗位
    async changepPsitionIds(e) {
      // console.log('00', e);
      // if (e.length == 0) {
      //   this.detail.positionAttributeIds = [];
      //   return;
      // }
      try {
        const { data } = await attributePullList({
          ids: this.detail.positionIds
        });
        // console.log('data', data);
        this.options.positionAttributeIds = data;
      } catch (e) {
        this.options.positionAttributeIds = [];
      }
    },
    // 更改岗位属性
    changePositionAttributeIds() {
      // this.detail.deptId = '';
    },
    // 提交
    createDetail(formName) {
      // console.log(this.detail);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.detail.yardIds.length);
          // if (this.detail.personType == 2 && !this.detail.yardIds.length) {
          //   this.$message({
          //     message: '请选择院区',
          //     type: 'warning'
          //   });
          // } else {
          let hintText = this.nameType == '新增' ? `新增${this.detail.name}` : `修改${this.detail.name}`;
          this.hint('create', hintText);
          // }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 确认提示
    hint(status, hintText, row) {
      this.$confirm(`${hintText}, 是否确认?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          switch (status) {
            case 'create':
              this.submitBrand(row);
              break;
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    // 提交接口
    async submitBrand() {
      // let params = {
      //   ...this.detail
      // };
      // let orgIds = '';
      // if (this.detail.personType == 2) {
      //   // this.detail.deptIds = [this.detail.deptIds];
      //   params.deptIds = params.deptIds.split(',');
      // } else {
      //   params.orgIds = JSON.stringify(this.detail.orgIds);
      // }
      if (this.detail.personType == 1 && this.detail.orgIds.length > 0) {
        this.detail.orgIds = [this.detail.orgIds];
      } else {
        this.detail.orgIds = [];
      }
      try {
        if (this.detail.personType == 2) {
          // if (this.detail.positionAttributeIds.includes(48)) {
          //   this.detail.deptIds = this.detail.deptId;
          // } else {
          this.detail.deptIds = [this.detail.deptId];
          // }
        }
        const res = this.nameType == '新增' ? await personAdd({
          ...this.detail
        }) : await personUpdate({
          ...this.detail
        });

        this.$notification('操作成功', 'success', res.msg);
        this.returnUpper();
      } catch (e) {
        // this.options.dept = [];
        this.detail.deptIds = [];
      }
      // console.log(res);
    },
    // 取消按钮
    closeDialog() { },
    // 返回
    returnUpper() {
      this.$store.dispatch('tagsView/delView', this.$route);
      this.$router.back();
    }
  }
};
</script>

<style lang="scss" scoped>
.add {
  background: #fff;
  .addOrderPopout {
    height: 80vh;
    // overflow-y: hidden;
  }
  .input {
    width: 100%;
  }
  .el-form-item {
    margin-bottom: 16px;
    width: 30%;
    ::v-deep.el-form-item__label {
      padding-bottom: 0;
      min-width: 100px;
      text-align: right;
    }
  }
  ::v-deep.el-dialog {
    height: calc(100vh - 80px);
    overflow-y: auto;
  }
  ::v-deep.el-dialog__body {
    padding: 0 20px 100px;
    position: relative;
  }
}

.el-form--label-left {
  // display: flex;
  // flex-wrap: wrap;
}
.el-form-item {
  display: flex;
  margin-right: 30px;
}
.footer {
  position: absolute;
  right: 50px;
  bottom: 80px;
}
</style>
